<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { numberToChinese } from '@/utils/numberToChinese';
import { getBookInformation } from '@/apis/bookInformation.js';
import { getCurrentInstance } from 'vue';
import { addBookShelfAPI, removeBookShelfAPI } from '@/apis/shelf';
import { dianzan,dis_dianzan } from '@/apis/dianzan'
import { historyRead } from '@/apis/historyRead'

const id = ref();
const isAdd = ref(false); // 默认设为未加入书架
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const isDian =ref(false)
const tagColorClass = () => {
  const classes = ['tag-blue', 'tag-yellow', 'tag-orange'];
  const randomIndex = Math.floor(Math.random() * classes.length);
  return classes[randomIndex];
};
const changeConcern = () => {
  console.log(isAdd.value)
  if (isAdd.value) {
    removeBookShelfAPI(route.params.id,proxy)
    ElMessage.success('移除书架成功');
  } else {
    addBookShelfAPI(route.params.id,proxy)
    // 如果用户未关注，则关注，并通过 ElMessage 再次询问用户
    ElMessage.success('加入书架成功');
  }
  // 切换关注状态
  isAdd.value = !isAdd.value;
}
const changeDianzan = () => {
  console.log(isDian.value)
  if (isDian.value) {
    dis_dianzan(route.params.id, proxy)
    ElMessage.success('取消点赞成功');
  } else {
    dianzan(route.params.id, proxy)
    // 如果用户未关注，则关注，并通过 ElMessage 再次询问用户
    ElMessage.success('点赞成功');
  }
  // 切换关注状态
  isDian.value = !isDian.value;
}
const bookInfo = ref();
const newChapter = ref({});

const getInformation = async() => {
  id.value = route.params.id;
  console.log(id.value)
  bookInfo.value = await getBookInformation(id.value,proxy);
  if(bookInfo.value === null){
    ElMessage.error('该书籍不存在');
  }
  console.log(bookInfo.value)
};

const toRead = async () => {
  bookInfo.value = await getBookInformation(route.params.id,proxy);
  console.log(bookInfo.value)
  if (bookInfo.value.chapter.length === 0) {
    ElMessage.error('该书籍暂无章节');
    return;
  }
  console.log(bookInfo.value.chapter)

  const chapterId = bookInfo.value.chapter[0].chapter_index;

  const chapterIndexOne = bookInfo.value.chapter.find(chapter => chapter.chapter_index === 1);
  console.log(bookInfo.value.chapter)
  console.log(chapterIndexOne)
  console.log(chapterId)
  
  await historyRead(route.params.id, chapterIndexOne.id, proxy)

  router.push(`/reader/${route.params.id}/${chapterId}`);
};

const addBookShelf = () => {
  ElMessageBox.confirm(
    '您是否要将此书加入到书架?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
      draggable: true,
    }
  )
    .then(() => {
      isAdd.value = true;
      console.log(isAdd.value)
      ElMessage({
        type: 'success',
        message: '加入书架成功',
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      });
    });
};


const closeBookShelf =  () => {
  ElMessageBox.confirm(
    '您是否要将此书移除书架?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
      draggable: true,
    }
  )
    .then(() => {false
      isAdd.value = false;
      console.log(isAdd.value)
      ElMessage({
        type: 'success',
        message: '移除书架成功',
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      });
    });
};
onMounted( async () => {
  await getInformation();
  isAdd.value = bookInfo.value.is_reading;
  isDian.value = bookInfo.value.is_liked;
  // newChapter.value.chapterNum = bookInfo.value.chapter[bookInfo.value.chapter.length - 1].chapter_index;
})
</script>
<template>
  <div class="bookCard" v-if="bookInfo!== undefined">
    <div class="img-text-container">
      <div class="img">
        <img width="225px" height="250px" :src="bookInfo.cover_url" :alt="bookInfo.name" />
      </div>
      <div class="text-container">
        <p class="title">{{ bookInfo.name }}</p>
        <div class="tags">
          <div v-for="tag in bookInfo.tag" :key="tag" :class="['rounded-border', tagColorClass(tag)]">
            {{ tag }}
          </div>
        </div>
        <div class="information-container">
<!--          <div class="information">-->
<!--            <p class="info-number">{{ bookInfo.search_number}}</p>-->
<!--            <p class="info-text">总阅读量</p>-->
<!--          </div>-->
          <div class="information">
            <p class="info-number">{{ bookInfo.like_number }}</p>
            <p class="info-text">推荐量</p>
          </div>
          <div class="information">
            <p class="info-number">{{ bookInfo.hot_number }}</p>
            <p class="info-text">热度</p>
          </div>
          <div class="information">
            <p class="info-number">{{ bookInfo.word_count }}</p>
            <p class="info-text">总字数</p>
          </div>
        </div>
        <!-- <div class="new">
          <p>最新章节:</p>
          <p class="new-chapter" @click="router.push(`/reader/${router.params.bookId}/${newChapter.chapterNum}`)">第{{
            (newChapter.chapterNum) }}章 {{ newChapter.title }}</p>
          <p>{{ bookInfo.updateTime }}</p>
        </div> -->
        <div class="button-container">
          <el-button type="danger" round @click="toRead">立即阅读</el-button>
          <div style="margin: 10px">
            <el-button type="primary" round @click="changeConcern">{{ isAdd ? '移除书架' : '加入书架'
              }}</el-button>
          </div>
          <el-button type="primary" round @click="changeDianzan">{{ isDian ? '取消点赞' : '点赞' }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.bookCard {
  display: flex;
  align-items: flex-start;
  height: 350px;
  max-width: 100%;
  width: 740px;
  overflow-x: hidden;
  box-sizing: border-box;
}
.img{
  width: 250px;
  height: 300px;
  overflow: hidden;
}
.img img {
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
}

.img img:hover {
  transform: scale(1.1);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}

.img-text-container {
  display: flex;
  align-items: center;
}

.img {
  margin-right: 20px;
}

.text-container {
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 30px;
  font-weight: bolder;
  margin: 10px 0;
}

.tags {
  display: flex;
  margin: 10px 10px 10px 0;
}

.rounded-border {
  background-color: white;
  display: inline-block;
  padding: 2px 6px;
  margin: 5px 5px 10px 0;
  border-radius: 10px;
  border: 1px solid transparent;
}

.tag-blue {
  color: #3498db;
  border-color: #3498db;
}

.tag-yellow {
  color: gold;
  border-color: gold;
}

.tag-orange {
  color: orange;
  border-color: orange;
}

.information-container {
  display: flex;
  flex-direction: row;
  margin: 0 10px 0 0;
}

.information {
  display: flex;
  flex-direction: row;
  /* align-items: baseline; */
  align-items: center;
  margin-right: 40px;
}

.info-number {
  font-size: 20px;
  font-family: Arial, sans-serif;
  margin-right: 2px;
}

.info-text {
  font-size: 10px;
  opacity: 0.7;
}

.new {
  display: flex;
  flex-direction: row;
  margin: 20px 0;
}

.new-chapter:hover {
  color: red;
}

.new p {
  margin-right: 20px;
}

.button-container {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>